package com.kuding.captcha;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.kuding.exceptions.VinusException;
import com.kuding.props.AliyunCaptchaProperties;

public class AliCaptchaComponent implements CaptchaComponent<CaptchaContent> {

	private final AliyunCaptchaProperties aliyunCapchaProperties;

	private final IAcsClient client;

	private final Log logger = LogFactory.getLog(getClass());

	public AliCaptchaComponent(AliyunCaptchaProperties aliyunCapchaProperties) {
		this.aliyunCapchaProperties = aliyunCapchaProperties;
		IClientProfile profile = DefaultProfile.getProfile(aliyunCapchaProperties.getRegionId(),
				aliyunCapchaProperties.getAccessKeyId(), aliyunCapchaProperties.getSecret());
		client = new DefaultAcsClient(profile);
		DefaultProfile.addEndpoint("cn-hangzhou", "afs", "afs.aliyuncs.com");
	}

	public AliyunCaptchaProperties getAliyunCapchaProperties() {
		return aliyunCapchaProperties;
	}

	public IAcsClient getClient() {
		return client;
	}

	@Override
	public boolean check(HttpServletRequest httpServletRequest, CaptchaContent capcha) {
		String remoteIp = httpServletRequest.getRemoteAddr();
		AuthenticateSigRequest request = new AuthenticateSigRequest();
		request.setSessionId(capcha.getSessionId());
		request.setSig(capcha.getSign());
		request.setToken(capcha.getToken());
		request.setScene(capcha.getScene());
		request.setAppKey(aliyunCapchaProperties.getAppKey());
		request.setRemoteIp(remoteIp);
		try {
			AuthenticateSigResponse response = client.getAcsResponse(request);
			if (response.getCode() == 100) {
				logger.debug("验证成功");
				return true;
			} else {
				logger.debug("验证失败：" + response.getDetail());
				return false;
			}
		} catch (ClientException e) {
			logger.error("验证出错", e);
			throw new VinusException("验证出错", e);
		}
	}
	
	

}
